import json
import random

from django import http
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View

from apps.book.models import BookGroup, Book, Book_Info, Book_Commit, Commit_Give_like
from apps.user.models import User_book


class Book_class(View):
    def get(self, request, uuid):

        # 获取分类数据
        book = BookGroup.objects.filter(id=uuid)
        if book:
            book = book[0]
        else:
            book = BookGroup.objects.filter(id=14)
        #     获取周推小说
        week = Book.objects.filter(group=book).order_by("-creat_time")

        # 获取连载小说
        new = Book.objects.filter(group=book, status=False).order_by("-creat_time")
        # 获取完本小说
        over = Book.objects.filter(group=book, status=True).order_by("-creat_time")

        # 右侧推荐数据
        new_pg = Paginator(new, 10)
        over_pg = Paginator(over, 10)
        pg = Paginator(week, 10)
        # 将倒数第二页掌握推荐数据
        new_tj = new_pg.page(new_pg.num_pages - 1)
        over_tj = over_pg.page(over_pg.num_pages - 1)

        week_pg = pg.page(1)
        # 编辑推荐
        bj = pg.page(pg.num_pages - 1)
        # 封面推荐
        fmtj = bj.object_list[5:]
        bj = bj.object_list[:5]

        content = {
            "book": book,
            "week_pg": week_pg,
            "bj": bj,
            "fmtj": fmtj,
            "new": new[:9],
            "over": over[:9],
            "new_tj": new_tj,
            "over_tj": over_tj,
            "user": request.user if request.user.id else None
        }
        return render(request, "book/channel.html", context=content)


class Book_info(View):
    def get(self, request, uuid):
        data = Book.objects.filter(id=uuid)
        if not data:
            return render(request, "404.html")
        # 获取当前小说的章节数据
        update_book_info = Book_Info.objects.filter(book=data[0]).order_by("-order_id")

        # 获取第一章
        first = update_book_info.last()
        # 获取最后一章
        if update_book_info:
            update_book_info = update_book_info[0]

        # 获取该小说是否在用户的书架中
        t_f = []
        if request.user.id:
            t_f = User_book.objects.filter(user=request.user, book=data, is_del=False)
        content = {
            "book": data[0],
            "update": update_book_info,
            "user": request.user if request.user.id else None,
            "first": first,
            "t_f": t_f
        }
        return render(request, "book/book_info.html", context=content)


class Book_info_catalog(View):
    def get(self, request, uuid):
        # 获取当前小说
        book = Book.objects.filter(id=uuid)
        num = request.GET.get("num", "1")
        if not book:
            return render(request, "404.html")
        # 获取当前小说的章节数据
        book_info = Book_Info.objects.filter(book_id=book).order_by("order_id")
        pg = Paginator(book_info, 99)
        page = pg.page(1)
        if num and num.isdigit():
            page = pg.page(int(num))
        page.num_pages = pg.num_pages
        first = book_info[0]
        # 获取该小说是否在用户的书架中
        t_f = []
        if request.user.id:
            t_f = User_book.objects.filter(user=request.user, book=book, is_del=False)
        content = {
            "book": book[0],
            "book_info": page,
            "user": request.user if request.user.id else None,
            "first": first,
            "t_f": t_f,
            "page": page
        }
        return render(request, "book/catalog.html", context=content)


class Book_Content(View):
    def get(self, request):
        book_id = request.GET.get("book")
        order_id = request.GET.get("num")
        if not all([book_id, order_id]):
            return render(request, "404.html")
        book = Book_Info.objects.filter(book_id=book_id, order_id=order_id)

        if not book:
            return render(request, "404.html")

        next_page = Book_Info.objects.filter(book_id=book_id, order_id__gt=order_id).order_by("order_id")

        prev_page = Book_Info.objects.filter(book_id=book_id, order_id__lt=order_id).order_by("-order_id")
        # 获取上一页下一页
        if prev_page:
            prev_page = prev_page[0]
        if next_page:
            next_page = next_page[0]
        commit = Book_Commit.objects.filter(chapter=book[0], is_deleted=False).order_by("-create_time")
        # 判断用户是否登录
        if request.user.id:
            # 判断用户书架中是否有这本书
            user_book = User_book.objects.filter(user=request.user, book_id=book_id)
            if user_book:
                # 将用户书架的阅读进度修改为当前的小说章节
                user_book[0].book_info = book[0]
                user_book[0].save()

        # 循环所有评论
        for i in commit:
            i.status = 3
            # 判断当前用户是否对该评论进行点赞或踩
            if request.user.id and i.commit_give_like_set.all().filter(author=request.user, is_del=False):
                # 给这个评论绑定状态， 评论或踩的状态
                i.status = i.commit_give_like_set.all().filter(author=request.user, is_del=False)[0].status
            i.zan_count = i.commit_give_like_set.all().filter(status=1).count()

        content = {
            "book": book[0],
            "prev_page": prev_page,
            "next_page": next_page,
            "user": request.user if request.user.id else None,
            "commit": commit
        }
        return render(request, "book/book_content.html", context=content)

    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        print(data)
        commit_id = data.get("commit_id")
        status = data.get("status")
        print(status, type(status))
        if not request.user.id:
            return http.JsonResponse({"code": "8520", "errmsg": "请先登录"})
        if not all([commit_id, status]):
            return http.JsonResponse({"code": "7410", "errmsg": "缺少数据"})
        if status not in [1, 2, "1", "2"]:
            return http.JsonResponse({"code": "74010", "errmsg": "数据错误"})
        # 查询用户之前是否对该评论进行点赞
        t_f = Commit_Give_like.objects.filter(author=request.user, book_commit_id=commit_id)
        # 如果有
        if t_f:
            # 判断是否是取消操作
            if status == t_f[0].status:
                # 如果是取消操作，将状态设置为3
                t_f[0].status = 3
                t_f[0].is_del = True
                t_f[0].save()
            # 如果不是重复操作，则将状态设置为当前状态
            else:
                t_f[0].status = status
                t_f[0].is_del = False
                t_f[0].save()
        else:
            book_commit = Book_Commit.objects.filter(id=commit_id)
            # 判断数据是否合格
            if book_commit:
                commit = Commit_Give_like.objects.create(author=request.user, status=status, book_commit=book_commit[0])
                commit.save()
            else:
                return http.JsonResponse({"code": "7410", "errmsg": "数据错误"})
        return http.JsonResponse({"code": "0", "errmsg": "操作成功"})
